import { Direction, UIConfig } from "./UIConfig";

/**
 * 瓦块节点的行列对象
 */
export default class Train {

    /**
     * 列(横)坐标
     */
    public x: number = 0;

    // 行(纵)坐标
    public y: number = 0;

    /**
     * 构造函数
     * @param x 列(横)坐标
     * @param y 行(纵)坐标
     */
    constructor(x: number | Train, y?: number) {
        this.set(x, y);
    }

    /**
     * 更新行列数据
     * @param x 列(横)坐标
     * @param y 行(纵)坐标
     */
    public set(x: number | Train, y?: number) {
        if (typeof x === 'number') {
            this.x = x;
            this.y = y || 0;
        }
        else {
            this.x = x.x;
            this.y = x.y;
        }
    }

    public copy(): Train {
        return new Train(this.x, this.y);
    }

    public isSame(x: number | Train, y?: number): boolean {
        if (typeof x === 'number')
            return this.x === x && this.y === y;
        else
            return this.x === x.x && this.y === x.y;
    }

    /**
     * 是否相邻
     */
    public isNearby(x: number | Train, y?: number): boolean {
        const obj = typeof x !== "number";
        const b = obj ? x.y : y || 0;
        const a = obj ? x.x : x;
        return Math.abs(this.x - a) + Math.abs(this.y - b) == 1;
    }

    /**
    * 获取临近的一个的坐标
    * @param d 方向
    */
    public getNearbyXY(d: Direction): Train {
        switch (d) {
            case Direction.Up:
                return this.y === UIConfig.ROW - 1 ? null : new Train(this.x, this.y + 1);
            case Direction.Down:
                return this.y === 0 ? null : new Train(this.x, this.y - 1);
            case Direction.Left:
                return this.x === 0 ? null : new Train(this.x - 1, this.y);
            case Direction.Right:
                return this.x === UIConfig.COL - 1 ? null : new Train(this.x + 1, this.y);
        }
    }

    public get string() {
        return "Train: (" + this.x + "," + this.y + ")";
    }

}